import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
const Login = () => import('@/views/login/index.vue')
const Home = () => import('@/views/home/index.vue')
const Question = () => import('@/views/question/index.vue')
const Video = () => import('@/views/video/index.vue')
const User = () => import('@/views/user/index.vue')
const Profile = () => import('@/views/user/profile.vue')
const Chat = () => import('@/views/user/chat.vue')
const Article = () => import('@/views/acticle/index.vue')
const Tabbar = () => import('@/components/app-tabbar.vue')
Vue.use(VueRouter)

const routes = [
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () =>
  //     import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
  {
    path: '/login',
    component: Login,
    // 路由元
    meta: {}
  },
  {
    path: '/',
    alias: '/home',
    components: { default: Home, bottom: Tabbar }
  },
  {
    path: '/question',
    components: { default: Question, bottom: Tabbar }
  },
  {
    path: '/user',
    components: { default: User, bottom: Tabbar },
    meta: {
      needLogin: true
    }
  },
  {
    path: '/video',
    components: { default: Video, bottom: Tabbar }
  },
  {
    path: '/user/profile',
    component: Profile,
    // 路由元做法
    meta: {
      needLogin: true
    }
  },
  {
    path: '/user/chat',
    component: Chat,
    meta: {
      needLogin: true
    }
  },
  {
    path: '/article/:id',
    components: {
      default: Article
    }
  }
]

const router = new VueRouter({
  routes
})

export default router
// 白名单
// const whitePath = ['/user', '/user/profile', '/user/chat']
//  导航守卫
router.beforeEach((to, from, next) => {
  if (store.getters['user/getToken']) {
    if (to.path.toLowerCase() === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    // if (to.path.toLowerCase().startsWith('/user')) {
    // 白名单写法
    // if (whitePath.includes(to.path.toLowerCase())) {
    // 路由元做法
    if (to.meta.needLogin) {
      next('/login?redirect=' + to.fullPath)
    } else {
      next()
    }
  }
})
